package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RunninGubUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Orders;
import com.ruoyi.system.domain.Productlist;
import com.ruoyi.system.domain.UserWorks;
import com.ruoyi.system.service.IOrdersService;
import com.ruoyi.system.service.IProductlistService;
import com.ruoyi.system.service.IUserWorksService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 作品Controller
 *
 * @author ruoyi
 * @date 2025-04-29
 */
@Api("作品信息管理")
@RestController
@RequestMapping("/system/works")
public class UserWorksController extends BaseController {


    private static final Logger log = LoggerFactory.getLogger(UserWorksController.class);

    @Autowired
    private IUserWorksService userWorksService;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IProductlistService productlistService;

    @Value("${img.upload}")
    private String IMG_UPLOAD_DIR;

    @Value("${img.request}")
    private String IMG_REQUEST_DIR;

    @Value("${img.requestUpload}")
    private String IMG_REQUEST_UPLOAD_DIR;


    /**
     *
     * @param file 上传文件
     * @param orderStore 门店ID
     * @param useImageName 底图ID
     * @return
     */
    @PostMapping("/imgTest")
    public String imgTest(@RequestParam("image") MultipartFile file,
                          @RequestParam("orderStore") String orderStore,
                          @RequestParam("useImageName") String useImageName) {
        int i = ThreadLocalRandom.current().nextInt(100);
        log.info("进入生图,进程:" + i);
        if (file.isEmpty()) {
            return "请选择要上传的图片";
        }

    /*    if (userWorksService.getUserGenImgCount(SecurityUtils.getUserId()) == 0) {
            return "生图次数不够";
        }*/
        try {
            // 创建存储目录（如果不存在）
            File uploadDir = new File(IMG_UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成唯一的文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get(IMG_UPLOAD_DIR, fileName);
            log.info("filePath:" + filePath.toString());


            String imgUrl;
            try {
                // 将上传的文件保存到指定目录
                Files.write(filePath, file.getBytes());
                String imgName = RunninGubUtils.upload(filePath.toString());
//                String taskId = RunninGubUtils.run(imgName,buildType);
                String taskId = RunninGubUtils.runT(imgName);
                imgUrl = RunninGubUtils.outputs(taskId);
                log.info(imgUrl);
                log.info("imgUrl:" + imgUrl);
                if ("".equals(imgUrl) || imgUrl == null) {
                    log.info("图片上传失败：img为空");
                    return "图片上传失败,请切换图片上传";
                }
            } catch (RuntimeException e) {
                log.info("图片上传失败,其他因素:{}", e.getMessage());
                return "图片上传失败，" + e.getMessage();
            }


            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 格式化时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddHHmmss");
            String orderId = now.format(formatter);

            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userId = SecurityUtils.getUserId();

            log.info("loginUser:" + loginUser);
            log.info("userId:" + userId);

            UserWorks userWorks = new UserWorks();
            userWorks.setWorkImage(imgUrl);
            userWorks.setUseImage(IMG_REQUEST_UPLOAD_DIR + fileName);
            log.info("fileName:" + fileName);

            userWorks.setWorkStatus(2L);
            userWorks.setCreateTime(DateUtils.getNowDate());
            userWorks.setHistoryOrder(orderId);
            userWorksService.insertUserWorks(userWorks, userId);


            Productlist productlist = productlistService.selectProductlistByProductId(Long.valueOf(useImageName));

            Orders order = new Orders();
            order.setOrderId(Long.valueOf(orderId));
            order.setOrderMoney(productlist.getProductSizeType().equals("0") ? new BigDecimal("4500") : new BigDecimal("3800"));
//            order.setOrderMoney(new BigDecimal("1"));
            order.setUserId(loginUser.getUserId());
//            order.setOrderTime(DateUtils.getNowDate());
            order.setOrderStatus(String.valueOf(0));
            order.setUseImageName(useImageName);
            order.setOrderStore(orderStore);

            ordersService.insertOrders(order);

            return  orderId;
        } catch (IOException e) {
            log.info("图片上传失败,其他因素:{}", e.getMessage());
            return "图片上传失败";
        }
    }

    @PostMapping("/buildImg")
    public String buildImg(@RequestParam("image") MultipartFile file,
                          @RequestParam("orderStore") String orderStore,
                          @RequestParam("buildType") String buildType,
                          @RequestParam("useImageName") String useImageName) {
        int i = ThreadLocalRandom.current().nextInt(100);
        log.info("进入生图,进程:" + i);
        if (file.isEmpty()) {
            return "请选择要上传的图片";
        }

        if (orderStore == null || "".equals(orderStore)) {
            return "请选择门店";
        }

        if (useImageName == null || "".equals(useImageName)) {
            return "请选择底图";
        }

        if (buildType == null || "".equals(buildType)) {
            return "请选择风格";
        }


    /*    if (userWorksService.getUserGenImgCount(SecurityUtils.getUserId()) == 0) {
            return "生图次数不够";
        }*/
        try {
            // 创建存储目录（如果不存在）
            File uploadDir = new File(IMG_UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 生成唯一的文件名
            String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get(IMG_UPLOAD_DIR, fileName);
            log.info("filePath:" + filePath.toString());


            String imgUrl;
            try {
                // 将上传的文件保存到指定目录
                Files.write(filePath, file.getBytes());
                String imgName = RunninGubUtils.upload(filePath.toString());
                String taskId = RunninGubUtils.run(imgName,buildType);
                imgUrl = RunninGubUtils.outputs(taskId);
                log.info(imgUrl);
                log.info("imgUrl:" + imgUrl);
                if ("".equals(imgUrl) || imgUrl == null) {
                    log.info("图片上传失败：img为空");
                    return "图片上传失败,请切换图片上传";
                }
            } catch (RuntimeException e) {
                log.info("图片上传失败,其他因素:{}", e.getMessage());
                return "图片上传失败，" + e.getMessage();
            }


            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 格式化时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddHHmmss");
            String orderId = now.format(formatter);

            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userId = SecurityUtils.getUserId();

            log.info("loginUser:" + loginUser);
            log.info("userId:" + userId);

            UserWorks userWorks = new UserWorks();
            userWorks.setWorkImage(imgUrl);
            userWorks.setUseImage(IMG_REQUEST_UPLOAD_DIR + fileName);
            log.info("fileName:" + fileName);

            userWorks.setWorkStatus(2L);
            userWorks.setCreateTime(DateUtils.getNowDate());
            userWorks.setHistoryOrder(orderId);
            userWorksService.insertUserWorks(userWorks, userId);


            Productlist productlist = productlistService.selectProductlistByProductId(Long.valueOf(useImageName));

            Orders order = new Orders();
            order.setOrderId(Long.valueOf(orderId));
            order.setOrderMoney(productlist.getProductSizeType().equals("0") ? new BigDecimal("4500") : new BigDecimal("3800"));
//            order.setOrderMoney(new BigDecimal("1"));
            order.setUserId(loginUser.getUserId());
//            order.setOrderTime(DateUtils.getNowDate());
            order.setOrderStatus(String.valueOf(0));
            order.setUseImageName(useImageName);
            order.setOrderStore(orderStore);

            ordersService.insertOrders(order);

            return  orderId;
        } catch (IOException e) {
            log.info("图片上传失败,其他因素:{}", e.getMessage());
            return "图片上传失败";
        }
    }


    /**
     * 查询作品列表
     */
    @ApiOperation("查询作品列表")
    @GetMapping("/list")
    public TableDataInfo list(UserWorks userWorks) {
        startPage();
        List<UserWorks> list;
        if (!SecurityUtils.isAdmin(getUserId())) {
            list = userWorksService.selectUserWorksList(userWorks, getUserId());
        } else {
            list = userWorksService.selectUserWorksList(userWorks, null);
        }
        return getDataTable(list);
    }

    /**
     * 获取生图次数
     */
    @ApiOperation("获取生图次数")
    @GetMapping("/getGenCount")
    public AjaxResult jugGenCount() {
        Long userId = getUserId();
        return success(userWorksService.getUserGenImgCount(userId));
//        return success(2);
    }

    /**
     * 导出作品列表
     */
    @Log(title = "作品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserWorks userWorks) {
        List<UserWorks> list;

        if (!SecurityUtils.isAdmin(getUserId())) {
            list = userWorksService.selectUserWorksList(userWorks, getUserId());
        } else {
            list = userWorksService.selectUserWorksList(userWorks, null);
        }
        ExcelUtil<UserWorks> util = new ExcelUtil<UserWorks>(UserWorks.class);
        util.exportExcel(response, list, "作品数据");
    }

    /**
     * 获取作品详细信息
     */
    @ApiOperation("获取作品详细信息")
    @ApiImplicitParam(name = "worksId", value = "作品ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping(value = "/{worksId}")
    public AjaxResult getInfo(@PathVariable("worksId") Long worksId) {
        return success(userWorksService.selectUserWorksByWorksId(worksId));
    }

    /**
     * 新增作品
     */
    @ApiOperation("新增作品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workStatus", value = "状态，0: 绘画中，1: 未进行制作，2: 已进行制作", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "workImage", value = "作品缩略图，存储base64", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "paintwork", value = "绘画作品缩略图，存储base64", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "paintStyle", value = "风格", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "historyOrder", value = "订单相关信息", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "useImage", value = "底图，存储base64", dataType = "String", dataTypeClass = String.class)
    })
    @Log(title = "作品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserWorks userWorks) {
        return toAjax(userWorksService.insertUserWorks(userWorks, getUserId()));
    }

    /**
     * 修改作品
     */
    @ApiOperation("修改作品")
    @Log(title = "作品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserWorks userWorks) {
        return toAjax(userWorksService.updateUserWorks(userWorks));
    }

    /**
     * 删除作品
     */
    @ApiOperation("删除作品")
    @ApiImplicitParam(name = "worksIds", value = "作品 ID 数组，多个 ID 用逗号分隔", required = true, dataType = "Long[]", paramType = "path", dataTypeClass = Long[].class)
    @Log(title = "作品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{worksIds}")
    public AjaxResult remove(@PathVariable Long[] worksIds) {
        return toAjax(userWorksService.deleteUserWorksByWorksIds(worksIds));
    }
}
